import { register } from 'register-service-worker'

// The ready(), registered(), cached(), updatefound() and updated()
// events passes a ServiceWorkerRegistration instance in their arguments.
// ServiceWorkerRegistration: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration

register(process.env.SERVICE_WORKER_FILE!, {
  // The registrationOptions object will be passed as the second argument
  // to ServiceWorkerContainer.register()
  // https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register#Parameter

  // registrationOptions: { scope: './' },

  register (swRegistration, context) {
    console.log('Service Worker has been registered for scope:', context.scope)
  },

  // https://web.dev/offline-cookbook/
  // When the SW is updated we will execute the callback
  updatefound () {
    console.log('New content is downloading.')
  },

  // When the SW is updated we will execute the callback
  updated (swRegistration, context) {
    console.log('New content is available; please refresh.')
    // Add a custom event and dispatch it.
    // Used to display of a 'refresh' banner following a service worker update.
    // Set the event payload to the service worker registration object.
    window.dispatchEvent(
      new CustomEvent('swUpdated', { detail: swRegistration })
    )
  },

  // When the SW is updated and the page is reloaded, the "offline" event is triggered and we can execute the callback
  offline () {
    console.log('No internet connection found. App is running in offline mode.')
  },

  // When there's an error, the error event is triggered and we can execute the callback
  error (err) {
    console.error('Error during service worker registration:', err)
  }
}) 